package org.example.day01;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zlxad
 * @version 1.0
 * @description: TODO
 * 给你一个字符串 s，字符串s首尾相连成一个环形 ，请你在环中找出'l'、'o'、'x' 字符都恰好出现了偶数次最长子字符串的长度
 * @date 2024/3/11 15:22
 */
public class test012 {
    public static int findLongestSubstring(String s) {
        int maxLength = 0;
        int totalLength = s.length();

        // 复制字符串并拼接在尾部，以处理环形字符串
        String doubledString = s + s;
        int doubledLength = doubledString.length();

        // 统计'l'、'o'、'x'的初始数量
        int lCount = 0, oCount = 0, xCount = 0;
        for (int i = 0; i < totalLength; i++) {
            char c = s.charAt(i);
            if (c == 'l') {
                lCount++;
            }
            if (c == 'o') {
                oCount++;
            }
            if (c == 'x') {
                xCount++;
            }
        }

        // 初始化滑动窗口的起始位置
        int start = 0;
        // 使用HashMap记录每个字符出现的次数
        Map<Character, Integer> charCountMap = new HashMap<>();
        charCountMap.put('l', lCount);
        charCountMap.put('o', oCount);
        charCountMap.put('x', xCount);

        // 遍历双倍长度的字符串
        for (int end = 0; end < doubledLength; end++) {
            // 移除窗口最左边的字符
            char leftChar = doubledString.charAt(start);
            charCountMap.put(leftChar, charCountMap.get(leftChar) - 1);

            // 添加窗口最右边的字符
            char rightChar = doubledString.charAt(end);
            charCountMap.put(rightChar, charCountMap.get(rightChar) + 1);

            // 如果窗口大小大于原字符串长度，则移动起始位置
            if (end - start + 1 > totalLength) {
                char leftCharToRemove = doubledString.charAt(start);
                charCountMap.put(leftCharToRemove, charCountMap.get(leftCharToRemove) - 1);
                start++;
            }

            // 检查是否所有字符都出现了偶数次
            if (charCountMap.get('l') % 2 == 0 && charCountMap.get('o') % 2 == 0 && charCountMap.get('x') % 2 == 0) {
                int currentLength = end - start + 1;
                maxLength = Math.max(maxLength, currentLength);
            }
        }

        return maxLength;
    }

    public static void main(String[] args) {
        String s = "loxollox";
        int result = findLongestSubstring(s);
        System.out.println("The length of the longest substring with even counts of 'l', 'o', and 'x' is: " + result);
    }
}
